package reports.builders;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

/**
 * Pdf report builder.
 * 
 * @author Ian Ryu
 */

public class PDFBuilder implements IBuilder<File>
{
  private final IBuilder<String> builder;
  private boolean                tableHasContent;

  public PDFBuilder()
  {
    builder = new HTMLBuilder();
  }

  @Override
  public PDFBuilder addTitle(String title)
  {
    builder.addTitle(title);
    return this;
  }

  @Override
  public PDFBuilder addSubTitle(String subTitle)
  {
    builder.addSubTitle(subTitle);
    return this;
  }

  @Override
  public PDFBuilder startTable(int columns)
  {
    builder.startTable(columns);

    tableHasContent = false;
    return this;
  }

  @Override
  public PDFBuilder addTableHeader(Iterator<String> headers)
  {
    builder.addTableHeader(headers);

    tableHasContent = true;
    return this;
  }

  @Override
  public PDFBuilder addRow(Iterator<String> row)
  {
    builder.addRow(row);

    tableHasContent = true;
    return this;
  }

  @Override
  public PDFBuilder endTable()
  {
    if (!tableHasContent)
      addRow(java.util.Arrays.asList(new String[]
      {
        "&nbsp;"
      }).iterator());

    builder.endTable();
    return this;
  }

  @Override
  public PDFBuilder insertPadding(int value)
  {
    builder.insertPadding(value);
    return this;
  }

  @Override
  public PDFBuilder addParagraph(String text)
  {
    builder.addParagraph(text);
    return this;
  }

  @Override
  public PDFBuilder addList(Iterator<String> list)
  {
    builder.addList(list);
    return this;
  }

  @Override
  public File getData()
  {
    try
    {
      Path path = Files.createTempFile(null, ".pdf");
      File file = path.toFile();
      OutputStream outputStream = new FileOutputStream(file);
      Document document = new Document(PageSize.LETTER_LANDSCAPE);
      PdfWriter writer = PdfWriter.getInstance(document, outputStream);
      document.open();

      String data = builder.getData().replace("table {", "table {font-size: 8pt;");

      XMLWorkerHelper.getInstance().parseXHtml(writer, document,
          new ByteArrayInputStream(data.getBytes("UTF-8")));

      document.close();
      return file;
    }
    catch (Exception e)
    {
      e.printStackTrace();
      return null;
    }
  }
}
